% find a candidate planar patch
function [fitlist,plane] = select_patch(points)

  %Finds the size of remaining points
  [L,D] = size(points);
  tmpnew = zeros(L,3);
  tmprest = zeros(L,3);

  % pick a random point until a successful plane is found
  success = 0;
  while ~success
    idx = floor(L*rand);
    pnt = points(idx,:);
  
    % find points in the neighborhood of the given point
    
    %This is the tolerance used for finding points in the neighborhood
    %of the given point
    DISTTOL = 0.2;
    fitcount = 0;
    restcount = 0;
    
    %Loop through every point
    for i = 1 : L
      %Find the distance between the neighboring points and the point
      dist = norm(points(i,:) - pnt);
      
      %If the point is close enough, add a fit count and store the 
      %point
      if dist < DISTTOL
        fitcount = fitcount + 1;
        %Matrix storing the coordinates of the points on the plane
        tmpnew(fitcount,:) = points(i,:);
      else
        restcount = restcount + 1;
        tmprest(restcount,:) = points(i,:);
      end
    end
    oldlist = tmprest(1:restcount,:);

    if fitcount > 10
      % fit a plane using the tmpnew matrix
      [plane,resid] = fitplane(tmpnew(1:fitcount,:));
        
      %If the plane fits the points well, keep it as a patch
      if resid < 0.1
        fitlist = tmpnew(1:fitcount,:);
        return
      end
    end
  end  
